import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

const String h5JS2FlutterByRunjavascript = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>flutter向JS传递数据-通过runJavaScript方式</title>
    <script type="text/javascript">
      function hiCalljs(msg){
        document.getElementById('resultTxt').innerHTML = 'Flutter传递过来的数据: ' + msg;
      }
      function hiCallJsWithResult(v1,v2){
        return parseInt(v1) + parseInt(v2)
      }
    </script>
</head>
<body>
    <div id="resultTxt">这里是展示flutter传递过来的数据</div>
</body>
</html>
''';

class Flutter2JsByRunjavascript extends StatefulWidget {
  const Flutter2JsByRunjavascript({super.key});

  @override
  State<Flutter2JsByRunjavascript> createState() =>
      _Flutter2JsByRunjavascriptState();
}

class _Flutter2JsByRunjavascriptState extends State<Flutter2JsByRunjavascript> {
  late WebViewController controller;

  get _loadBtn => FilledButton(
    onPressed: () {
      controller.loadHtmlString(h5JS2FlutterByRunjavascript);
    },
    child: Text('加载H5', style: TextStyle(color: Colors.white)),
  );

  get _fireData => FilledButton(
    onPressed: () async {
      controller.runJavaScript('hiCalljs("Hello from Flutter")');
      var result = await controller.runJavaScriptReturningResult(
        'hiCallJsWithResult(1, 2)',
      );
      debugPrint('result: $result');
    },
    child: Text('传递数据', style: TextStyle(color: Colors.white)),
  );

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter向JS传递数据-通过runJavaScript方式'),
        actions: [_loadBtn, _fireData],
      ),
      body: WebViewWidget(controller: controller),
    );
  }
}
